package com.yhzc.webdemo;

import com.yhzc.dao.UserDao;
import com.yhzc.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
        Map<String, String[]> map = request.getParameterMap(); //创建要封装数据的对象
        User user = new User();
       try {
            //封装数据
            BeanUtils.populate(user, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //去数据库中查询用户,可以直接放查询代码;建议使用dao
        UserDao userDao = new UserDao();
        User loginUser = userDao.login(user);
        response.setContentType("text/html;charset=utf-8");
        if (loginUser != null) {
            response.getWriter().write("登录成功！！！");
            response.setHeader("refresh", "5;http://www.itcast.cn");//等待
            //response.sendRedirect("www.taobao.com");//重定向
        } else {
            request.setAttribute("name", request.getParameter("username"));
            request.getRequestDispatcher("/loginFail").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
